<?php

namespace App\Console\Commands;

use App\Services\WechatService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use EasyWeChat;

class getOrderExpressInfos extends Command
{
    protected $wechatService;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book-shop:get-order-express-infos';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取订单物流轨迹';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(WechatService $wechatService)
    {
        parent::__construct();
        $this->wechatService = $wechatService;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 在命令行打印一行信息
        $this->info("开始获取...");

        $officialAccount = EasyWeChat::officialAccount(); // 公众号
        $orders = DB::table('orders')->where('is_express',1)->where('state',2)->get();
        if(!empty($orders))
        {
            foreach ($orders as $v)
            {
                if(empty($v->express_waybill_id) || empty($v->express_delivery_id) || empty($v->user_openid))
                {
                    continue;
                }

                $ret = $this->wechatService->getExpressPath($v->user_openid, $v->no, $v->express_waybill_id, $v->express_delivery_id);
                //$str = '{"openid": "oykEg5WGTi181uPuJUX5jT7jlvr4", "delivery_id": "ZTO", "waybill_id": "73111684232979","path_item_num": 3, "path_item_list": [{"action_time": 1533052800, "action_type": 100001, "action_msg": "快递员已成功取件"}, {"action_time": 1533062800, "action_type": 200001, "action_msg": "快件已到达xxx集散中心，准备发往xxx"}, {"action_time": 1533072800, "action_type": 300003, "action_msg": "快递员已出发，联系电话xxxxxx"}]}';
                //$ret = json_decode($str,true);
                //var_dump($ret);
                /**
                 * 100001 	揽件阶段-揽件成功
                 * 100002 	揽件阶段-揽件失败
                 * 100003 	揽件阶段-分配业务员
                 * 200001 	运输阶段-更新运输轨迹
                 * 300002 	派送阶段-开始派送
                 * 300003 	派送阶段-签收成功
                 * 300004 	派送阶段-签收失败
                 * 400001 	异常阶段-订单取消
                 * 400002 	异常阶段-订单滞留
                */
                if(!empty($ret['path_item_list']))
                {
                    $last_item = $ret['path_item_list'][0];

                    $data = [
                        'order_id'          => $v->id,
                        'order_no'          => $v->no,
                        'delivery_id'       => $ret['delivery_id'],
                        'waybill_id'        => $ret['waybill_id'],
                        'path_item_num'     => $ret['path_item_num'],
                        'path_item_list'    => json_encode($ret['path_item_list']),
                        'last_action_time'  => $last_item['action_time'],
                        'last_action_type'  => $last_item['action_type'],
                        'last_action_msg'   => $last_item['action_msg'],
                    ];

                    DB::table('order_express_infos')->insert($data);


                    if($last_item['action_type'] == 300003)
                    {
                        //签收
                        DB::table('orders')->where('id',$v->id)->update(['state' => 3,'done_at' => $last_item['action_time']]);

                        $first_book = DB::table('order_items')->where('order_id',$v->id)->orderBy('id','asc')->first();
                        $keyword2 = "《".$first_book->book_title."》...共".$v->amount.'本书';

                        $user = DB::table('users')->select(['id','unionid'])->where('id',$v->user_id)->first();
                        $wechat_user = DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                        if(!empty($wechat_user))
                        {
                            $openid = $wechat_user->openid;

                            $first = "您购买的书已签收成功，订单完成\r\n";
                            $officialAccount->template_message->send([
                                'touser'        => $openid,
                                'template_id'   => 'gzUKsyRsPuqgPK5_hsQQvrUNZVvOYPryyaEry5VLjg8',
                                'url'  => '',
                                'miniprogram' => [
                                    'appid'     => config('wechat.mini_program.default.app_id'),
                                    'path'  => '/pages/order/order-detail/order-detail?id='.$v->id,
                                ],
                                'data' => [
                                    'first'     => $first,
                                    'keyword1'  => $v->no,
                                    'keyword2'  => $keyword2,
                                    'keyword3'  => $v->price.'元',
                                    'keyword4'  => $v->address_province_name.$v->address_city_name.$v->address_area_name.$v->address,
                                    'keyword5'  => date('Y-m-d H:i:s',$v->created_at)."\r\n",
                                    'remark'    => '点击“详情”可查看订单与物流详情。如对订单有疑问，可在小程序内咨询在线客服。'
                                ],
                            ]);

                        }
                    }
                }
            }
        }

        $this->info("获取成功...");
    }
}
